package com.zdy.demo;

/**
 * 第4题
 * 将一个字符串中的空格替换成"%20"
 * @author deyou
 * @version 1.0
 * @date 2021/5/19 17:09
 */

public class ReplaceBlank04 {

    public static String replaceBank1(String input){
        if(input == null){
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) == ' '){
                stringBuffer.append("%20");
            }else{
                stringBuffer.append(input.charAt(i));
            }
        }

        return stringBuffer.toString();
    }

    public static String replaceBank2(String input){

        if(input == null){
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) == ' '){
                sb.append("%20");
            }else{
                sb.append(input.charAt(i));
            }
        }

        return sb.toString();
    }

    /**
     * 解法三: 从后往前复制
     * @param input
     * @return
     */
    public static String replaceBank3(String input){

        if(input == null){
            return null;
        }
       //求出添加空格后数组长度
        int bankNum = 0;
        int length = input.length();
        for (int i = 0; i < input.length(); i++) {
            if(input.charAt(i) == ' '){
                bankNum++;
            }
        }

        int index = length + bankNum * 2;
        char[] chars = new char[index-1];
      //从后往前改变数组
        for (int i = input.length()-1; i >= 0; i--) {
            if(input.charAt(i) == ' '){
                chars[index--] = '0';
                chars[index--] = '2';
                chars[index--] = '%';
            }else {
                chars[index--] = input.charAt(i);
            }
        }

        return String.valueOf(chars);
    }
}
